<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-10-17 16:31:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Repositories\ProOutsourcingProductDetailRepository;
use App\Repositories\ProOutsourcingProductRepository;
use Illuminate\Support\Facades\DB;

/**
 * @property ProOutsourcingProductRepository $repository
 * @property ProOutsourcingProductDetailRepository $details 
 * @method static mixed delete($data)
 */
class OutsourcingProductService extends Service
    {
    public function boot(
        ProOutsourcingProductRepository $repository,
        ProOutsourcingProductDetailRepository $details,
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        }

    public function list()
        {
        // DB::enableQueryLog();
        $data = $this->repository->condition(request())->getGrid();
        // dd(DB::getQueryLog());

        return $data;
        }
    public function details()
        {
        $data = $this->details->condition(request())->getGrid();
        return $data;
        }

    public $whereFields = [
        'material_id' => ['key' => 'material_id'],
        'location_id' => ['key' => 'location_id'],
    ];
    protected function save()
        {
        $request = request();
        $data    = $request->toArray();
        // dd($data);
        // DB::enableQueryLog();
        unset($data['car_id'], $data['carry_id'], $data['car'], $data['carry']);
        $data['type_id']    = 1;
        $data['company_id'] = $data['outfactory_id'];
        $attachments        = $data['attachments'];
        $data               = $this->repository->autosave($data);

        //关联库存
        $cp_location_id = $this->addUseStorage($data);
        //创建收货单
        $data->finish_code = $this->createFinish($data, $attachments, $cp_location_id, $request->car, $request->carry, $request->car_id, $request->carry_id)[0]->code;
        return $data->save();
        }

    /**
     * @return \Illuminate\Database\Eloquent\Model
     */
    private function createFinish($data, $attachments, $cp_location_id, $car, $carry, $car_id, $carry_id)
        {

        $finish_data = [
            'billdate'    => $data->billdate,
            'remark'      => $data->remark,
            'company_id'  => $data->outfactory_id,
            'car_id'      => $car_id,
            'carry_id'    => $carry_id,
            'car'         => $car,
            'carry'       => $carry,
            'attachments' => $attachments,
            'details'     => [
                [
                    'quantity'           => $data->quantity,
                    'auxiliary_quantity' => $data->auxiliary_quantity,
                    'remark'             => $data->remark,
                    'price'              => $data->price,
                    'amount'             => $data->amount,
                    'extra_cost'         => $data->extra_cost,
                    'company_id'         => $data->outfactory_id,
                    'customer_id'        => $data->customer_id,
                    'unit_id'            => $data->unit_id,
                    'location_id'        => $data->location_id,
                    'old_location_id'    => $cp_location_id,
                    'material_id'        => $data->material_id,
                    'batchno'            => $data->batchno,
                    'type_id'            => 2,
                    'dyelot'             => $data->dyelot,
                    'color_name'         => $data->color_name,
                    'iscustomer'         => $data->iscustomer,
                ]
            ]
        ];
        return OutsourcingFinishService::audit(OutsourcingFinishService::save($finish_data));
        }
    private function addUseStorage($data)
        {
        //获取原料库位
        $storageLocation      = $data->outfactory->getLocation(0);
        $material_location_id = $data->outfactory->getLocation(1);
        //原料数量
        $material_quantity = 0;
        $data->details->filter(function ($v) use ($material_location_id, &$material_quantity, $data)
            {
            $v->location_id = $material_location_id;
            $v->setWhere($this->whereFields)
                ->setOutSoucing()
                ->useStorage("委外生产-主材出库", $data->code)
                ->subStorage();
            $material_quantity += $v->quantity;

            $delivery = $v->delivery;
            if ($delivery) {
                $delivery->delivery_quantity += $v->quantity;
                $delivery->save();
                }
            });
        $data->raws->filter(function ($v) use ($material_location_id)
            {
            $v->location_id = $material_location_id;
            $v->setWhere($this->whereFields)
                ->setOutSoucing()
                ->useStorage("委外生产-原料出库")
                ->subStorage();
            });
        $data->material_quantity = $material_quantity;
        $data->mergeWhere(['location_id' => $storageLocation])->addStorage("委外生产-成品入库");



        return $storageLocation;
        }
    protected function delete($ids = null)
        {
        $need_delete_finish = $ids == null;
        $ids                = $ids ?? $this->getRequestIds();
        $this->repository->whereIn("id", $ids)->get()->filter(function ($v) use ($need_delete_finish)
            {

            //删除关联单 收货单
            $need_delete_finish && OutsourcingFinishService::delete([$v->finish_code]);
            //原料数量
            $material_quantity = 0;
            $v->details->filter(function ($vv) use (&$material_quantity)
                {
                $vv->isSub() && $vv->nosubStorage();
                $vv->isUse() && $vv->nouseStorage();
                $material_quantity += $vv->quantity;
                $delivery          = $vv->delivery;
                if ($delivery) {
                    $delivery->delivery_quantity -= $material_quantity;
                    $delivery->save();
                    }
                $vv->delete();
                });
            $v->raws->filter(function ($vv)
                {
                $vv->isSub() && $vv->nosubStorage();
                $vv->isUse() && $vv->nouseStorage();
                $vv->delete();
                });
            $v->noaddStorage();
            $v->delete();

            });

        return $ids;
        }
    }